package com.ai.databao.web.system.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ai.databao.common.vo.comm.StaffInfoVo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ai.databao.web.system.util.StaffSessionUtil;

/**
 * 是否登录省份验证
 * 
 * @author lixc
 *
 */
public class LoginFilter implements Filter {

	public String loginPage = "/login";// 在web.xml中配置
	public String mainPage = "/main/pageInit";// 在web.xml中配置

	public static final String sessionOutPage = "/system/sessionOut"; // 写死在这，因为不会再修改
	public static final String noAuthPage = "/system/noAuth";// 写死在这，因为不会再修改

	public String[] IGNORE_SUFFIX = {};// 在web.xml中配置

	public Object[] NOTLOGIN_PAGES = {};// 在web.xml中配置
	public Object[] NEEDLOGIN_PAGES = {};// 在web.xml中配置

	private static Logger logger = LoggerFactory.getLogger(LoginFilter.class);

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpSession session = request.getSession();
		
		String uri = request.getServletPath();
		
		// 过滤不需要权限控制的Url
		if (shouldFilter(request) == false) {
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}

		if (uri.endsWith(this.loginPage)) {
			filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        if(uri.indexOf("/login/check")!=-1){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

		//没有登录时需要先登录
		StaffInfoVo staff = StaffSessionUtil.getStaffInfo(session);
		if(null == staff){
			response.sendRedirect(request.getContextPath() + loginPage);
			return;
		}

//        if(staff == null){
//
//            staff = new StaffInfoVo();
//            staff.setUserId("admin");
//            staff.setUserName("超级管理员");
//            ClassPathResource resource = new ClassPathResource("/devMenu.json", LoginFilter.class);
//            List<MenuDisplayVO> menus = new ObjectMapper().readValue(resource.getInputStream(),new TypeReference<List<MenuDisplayVO>>(){});
//
//            processMenus(menus,staff,session);
//
//            // 设置登陆信息
//            StaffSessionUtil.setStaffInfo(session, staff);
//        }
        
//        if (uri.endsWith(this.loginPage)) {
//            response.sendRedirect(request.getContextPath() + loginPage);
//            return;
//        }
        
        filterChain.doFilter(servletRequest, servletResponse);
        return;
		
	}


	/**
	 * 过滤指定后缀文件不走Filter
	 * 
	 * @param request
	 * @return
	 */
	private boolean shouldFilter(HttpServletRequest request) {
		String uri = request.getRequestURI().toLowerCase();

		for (String suffix : IGNORE_SUFFIX) {
			if (uri.endsWith(suffix)) {
				return false;
			}
		}

		return true;
	}


	/**
	 * web容器初始化
	 */
	@Override
	public void init(FilterConfig config) throws ServletException {
		String loginPage = config.getInitParameter("loginPage");
		if (StringUtils.isNotBlank(loginPage)) {
			this.loginPage = loginPage;
		}

		String mainPage = config.getInitParameter("mainPage");
		if (StringUtils.isNotBlank(mainPage)) {
			this.mainPage = mainPage;
		}

		String ignore_suffix = config.getInitParameter("ignore_suffix");
		if (StringUtils.isEmpty(ignore_suffix) == false)
			IGNORE_SUFFIX = ignore_suffix.split(",");

		String notlogin_pages = config.getInitParameter("notlogin_pages");
		if (StringUtils.isEmpty(notlogin_pages) == false)
			NOTLOGIN_PAGES = notlogin_pages.split(",");

		String needlogin_pages = config.getInitParameter("needlogin_pages");
		if (StringUtils.isEmpty(needlogin_pages) == false)
			NEEDLOGIN_PAGES = needlogin_pages.split(",");

	}

	/**
	 * 判断是否是Ajax请求
	 * 
	 * @param request
	 * @return
	 */
	private boolean isAjaxRequest(HttpServletRequest request) {

		String requestedWith = request.getHeader("x-requested-with");
		// 表示是一个AJAX POST请求
		if ("XMLHttpRequest".equalsIgnoreCase(requestedWith)) {
			return true;
		}
		return false;
	}
}
